package com.wjm.hdfsjavaapi.java;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.IOException;
import java.net.URI;


public class hdfs_test {
    static Configuration conf = new Configuration();
    static FileSystem fileSystem;

    public static void main(String [] args)throws Exception{
        upload();
        //download();
    }
     /**
     *  查看文件
     */
    public static void Getlist() throws Exception {
        fileSystem = FileSystem.get(conf);
        Path path = new Path("/");
        FileStatus[] list = fileSystem.listStatus(path);
        for (FileStatus f : list) {
            System.out.println(f);
        }

    }

    /**
     * 将HDFS下载到本地
     */
    public static void download() throws Exception{
        fileSystem = FileSystem.get(conf);
        fileSystem.copyToLocalFile(false,new Path("/a.php"),new Path("E:/"),true);
        fileSystem.close();

    }

    /**
     * 将文件上传到HDFS
     */
    public static void upload() throws Exception{
        fileSystem = FileSystem.get(conf);
        fileSystem.copyFromLocalFile(false,new Path("G:/b.txt"), new Path("/"));
        fileSystem.close();
    }

    /**
     * 将HDFS中文件名称进行修改
     */
    public static void update() throws Exception{
        fileSystem=FileSystem.get(new URI("hdfs://hadoop1:9000"),conf,"hadoop");
        Path oldName=new Path("/a.php");
        Path newName=new Path("/aa.php");
        fileSystem.rename(oldName,newName);
    }

    /**
     * 创建目录和文件
     */
    public static void create() throws Exception{
        fileSystem=FileSystem.get(new URI("hdfs://hadoop1:9000"),conf,"hadoop");
        Path path=new Path("/a.txt");
        fileSystem.mkdirs(path);
    }

    /**
     * 追加内容到HDFS文件中
     */
    public static void list() throws Exception{
        fileSystem=FileSystem.get(new URI("hdfs://hadoop1:9000"),conf,"hadoop");
        String countName="Hello HDFS";
        Path path=new Path("/hello.txt");
        byte[] bytes=countName.getBytes();
        FSDataOutputStream fsDataInputStream=fileSystem.append(path);
        fsDataInputStream.write(bytes);
    }

}
